package com.wnnight.wys.web.car;


import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wnnight.wys.entity.car.Car;
import com.wnnight.wys.groupInterface.AddGroup;
import com.wnnight.wys.groupInterface.AlterGroup;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.service.car.CarService;
import com.wnnight.wys.vo.ResultVo;
import com.wnnight.wys.vo.car.CarDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName: CarController
 * @Description: car控制器
 * @author: CHX42
 * @date: 2022/8/28-18:42
 * @version: v1.0
 */
@RestController
@RequestMapping("/api/v1/car/car")
@Slf4j
@Transactional
public class CarController {
    @Autowired
    private CarService carService;

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('car:car:add')")
    public ResultVo<?> add(@RequestBody @Validated({AddGroup.class}) Car car) {
        log.debug("增加车辆");
        car.setRegTime(DateUtil.now());
        //到期时间处理
        car.setEndTime(String.valueOf(DateUtil.offsetMonth(DateUtil.parse(car.getRegTime()), car.getXfTime() * 3)));
        car.setIsDelete("n");
        car.setStatus("y");
        String phone = car.getPhone();
        Integer id = carService.getIdByPhone(phone);
        if (id != null) {
            car.setOwner(null);
            car.setLandlordId(id);
        }
        carService.insert(car);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('car:car:upd')")
    public ResultVo<?> update(@RequestBody @Validated({AlterGroup.class}) Car car) {
        log.debug("修改车辆信息");
        QueryWrapper<Car> carUpWrapper = new QueryWrapper<>();
        Integer likeXfTime = car.getXfTime();
        if (likeXfTime!=null) {
            Car thisCar = carService.getById(car.getId());
            car.setEndTime( String.valueOf(DateUtil.offsetMonth(DateUtil.parse(thisCar.getEndTime()), car.getXfTime() * 3)));
        }
        car.setCarNum(null);
        car.setIsDelete("n");
        car.setStatus("y");
        carUpWrapper.eq(true, "wys_car.id", car.getId());
        carService.update(car, carUpWrapper);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/getCarInfo")
    @PreAuthorize("hasAuthority('car:car:info')")
    public ResultVo<?> getCarInfo(@RequestBody Car car) {
        log.debug("车辆详情");
        QueryWrapper<Car> carWrapper = new QueryWrapper<>();
        carWrapper.eq("wys_car.id", car.getId());
        Page<Car> backCar = carService.getPage(new Page<>(1, 1), carWrapper);
        return new ResultVo<>(backCar.getRecords().get(0));
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('car:car:list')")
    public ResultVo<?> list(@RequestBody CarDataVo<Car, Car> carDataVo) {
        log.debug("车辆列表");
        QueryWrapper<Car> carWrapper = new QueryWrapper<>();
        String likeCarNum = carDataVo.getData().getCarNum();
        String likeName = carDataVo.getData().getName();
        String likeOwner = carDataVo.getData().getOwner();
        String likePhone = carDataVo.getData().getPhone();
        carWrapper.like(StringUtils.hasText(likeCarNum), "wys_car.car_num", likeCarNum);
        carWrapper.like(StringUtils.hasText(likeName), "wys_landlord.name", likeName);
        carWrapper.like(StringUtils.hasText(likePhone), "wys_landlord.phone", likePhone);
        carWrapper.like(StringUtils.hasText(likeOwner), "wys_car.owner", likeOwner);
        Page<Car> backCars = carService.getPage(new Page<>(carDataVo.getPagePlus().getCurrent(), carDataVo.getPagePlus().getSize()), carWrapper);
        return new ResultVo<>(backCars);
    }


    @PostMapping("/getbylandlordid")
//    @PreAuthorize("hasAuthority('car:car:landcar')")
    public ResultVo<?> getByLandlordId(HttpServletRequest request) {
        log.debug("房东车辆列表");
        String jwt = request.getHeader("jwt");
        Integer id =(Integer) JwtUtils.getInfo(jwt, "id");
        return new ResultVo<>(carService.getByLandlordId(id));
    }


    @PostMapping("/download")
//    @PreAuthorize("hasAuthority('car:car:dlod')")
    public void downLoad(@RequestBody CarDataVo<Car,Car> carDataVo, HttpServletResponse response) throws IOException {
        QueryWrapper<Car> carWrapper = new QueryWrapper<>();
        String likeCarNum = carDataVo.getData().getCarNum();
        String likeName = carDataVo.getData().getName();
        String likeOwner = carDataVo.getData().getOwner();
        String likePhone = carDataVo.getData().getPhone();
        carWrapper.like(StringUtils.hasText(likeCarNum), "wys_car.car_num", likeCarNum);
        carWrapper.like(StringUtils.hasText(likeName), "wys_landlord.name", likeName);
        carWrapper.like(StringUtils.hasText(likePhone), "wys_landlord.phone", likePhone);
        carWrapper.like(StringUtils.hasText(likeOwner), "wys_car.owner", likeOwner);
//        List<Car> records =(List) carService.listObjs();
        Page<Car> backCars = carService.getPage(new Page<>(carDataVo.getPagePlus().getCurrent(), carDataVo.getPagePlus().getSize()), carWrapper);
        List<Car> records = backCars.getRecords();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("车辆表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Car.class).sheet("车辆表").doWrite(records);
    }
}